# 宙斯改版，把这个也改一下
# ---------
# ------
# ---


import os
import time
import requests
import json
import sys

# 获取项目文件路径
current_dir = os.path.dirname(__file__)
# 提取项目根路径
root_dir = os.path.abspath(os.path.join(current_dir, os.pardir))
# 将项目根路径存入，以便命令行运行时可以成功引包
sys.path.append(root_dir)

from handle_yaml import get_config
from 红妹妹审批.log import logger

# 获取当前文件路径，拼接json配置文件，生成路径，以供后面使用
path = os.path.dirname(__file__)
json_file_path = path + '/token.json'

servers = get_config('servers')[0]  # 从配置文件读取需要监控的服务，以供下面使用
creators = get_config('creators')[0]  # 从配置文件读取需要监控的审批人，以供下面使用
username = get_config('username')  # 从配置文件读取用户名，以供下面使用
password = get_config('password')  # 从配置文件读取密码，以供下面使用

logger.log_info(f'{len(servers)}个服务{servers}')
logger.log_info(f'{len(creators)}个用户{creators}')


# 获取最新token，完成token替换
def get_token():
    url = "http://zeus.corp.hongsong.club/portal/prod/api/login"

    payload = json.dumps({
        "username": username,
        "password": password
    })
    headers = {
        'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
        'Content-Type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)

    token = response.json()['data']['token']

    # 读取token配置文件中的内容
    with open(json_file_path, 'r') as f:
        data = json.load(f)
    # 将获取到的接口的token，写入到data中
    data['token'] = token
    # 将data再次写入token文件，完成token的替换
    with open(json_file_path, 'w') as f1:
        f1.write(json.dumps(data))
    logger.log_info('token替换完成')


# 调用审核接口，传入需要审核的任务id
def check_approved(approvalId):
    url = f"https://zeus.corp.hongsong.club/portal/prod/api/v2/approval/approved/{str(approvalId)}"
    url01 = f"https://zeus.corp.hongsong.club/portal/app/audit/approvalFlow/{str(approvalId)}?decision=APPROVE"
    logger.log_info(url01)
    payload = json.dumps({
        "decision": "APPROVE",
        "comment": "1"
    })

    headers = {
        'authorization': token,
        'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
        'Content-Type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)
    # print(response.text)
    logger.log_info(response.text)
    # 如果有如下返回，说明token失效，需要替换token文件中的token
    if response.json()['status']['des'] == '认证失效' and response.json()['status']['code'] == 100004:
        get_token()  # 替换token
        logger.log_info('替换完成，下一次执行生效')
    elif response.json()['status']['des'] == '成功':
        logger.log_info('审批完成')


# 处理服务列表数据，并调用审核接口
def handle_data(server_name):
    # 定义请求地址
    url = "http://zeus.corp.hongsong.club/portal/prod/api/deployTask/getTaskList"
    # 定义请求头
    headers = {
        'Authorization': token,
        'Content-Type': 'application/json'
    }
    # 定义请求体，对服务名遍历
    payload = json.dumps({
        "appCode": server_name,
        "env": "test",  # 只要测试环境的
        "startIndex": 0,
        "pageSize": 5
    })
    try:
        # 请求接口
        response = requests.request("POST", url, headers=headers, data=payload)
    except requests.exceptions.RequestException as e:
        logger.log_info("请求接口发生错误:", e)
    except KeyError as e:
        logger.log_info("解析JSON数据发生错误:", e)
    except Exception as e:
        logger.log_info("发生未知错误:", e)
    try:
        # 获取响应中的data
        datas = response.json()['data']
        for data in datas:
            # 判断状态是PENDING，审批人在审批人列表中，且没有审批记录的
            if data['status'] == 'PENDING' and data['creator'] in creators and len(
                    data['approvalRequest']['records']) == 0:
                # and datas[i]['auditStatus'] == 0   接口里面这个字段去掉了，判断条件也去掉
                taskId = data['taskId']  # 取id
                approvalId = data['approvalRequest']['id']  # 取审批id
                creator = data['creator']  # 取审批人
                deployBranch = data['deployBranch']  # 取分支
                appCode = server_name  # 取服务名
                scope = data['scope']  # 取影响范围

                logger.log_info('=====>准备审批，服务名：%s，id是：%s，审批id：%s，分支：%s，提交人：%s，范围：%s' % (
                    appCode, taskId, approvalId, deployBranch, creator, scope))
                # 执行审核操作
                check_approved(approvalId)

    except Exception as e:  # 报错后兜底逻辑。防止程序中断。
        logger.log_info(e)
        logger.log_info('解析数据出现错误------------------------------------------------')
        logger.log_info(response.text)
    time.sleep(0.3)


if __name__ == '__main__':
    while True:
        # 获取配置文件中的token
        with open(json_file_path, 'r') as f:
            data = json.load(f)
        token = data['token']
        for server in servers:
            # print(server)
            handle_data(server)

        # 执行获取审批任务列表数据的方法
        # 执行处理数据并审批的方法
        # handle_datas_to_examine(datas)
        # 等待
        # time.sleep(10)
        # print(time.strftime('%Y-%m-%d %H:%M:%S'))
        logger.log_info('=_=')
